package com.my.controller;

import com.github.pagehelper.PageInfo;
import com.my.pojo.ProductInfo;
import com.my.pojo.vo.ProductInfoVo;
import com.my.service.ProductInfoService;
import com.my.service.impl.ProductInfoServiceImpl;
import com.my.utils.FileNameUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/prod")
public class ProductInfoAction {
    //每页显示的记录数
    public static int PAGE_SIZE = 5;
    //异步上传的图片名称
    String saveFileName = "";

    @Autowired
    ProductInfoService productInfoService;

    //获取全部商品（不分页）
    @RequestMapping("/getAll")
    public String getAll(HttpServletRequest request){
        List<ProductInfo> list = productInfoService.getAll();
        request.setAttribute("list",list);
        return "product";
    }

    //显示第一页的5条数据
    @RequestMapping("/split")
    public String split(HttpServletRequest request){
        PageInfo info = null;
        Object vo = request.getSession().getAttribute("prodVo");
        if(vo != null){
            info = productInfoService.splitPageCondition((ProductInfoVo) vo,PAGE_SIZE);
            request.getSession().removeAttribute("prodVo");
        }else{
            info = productInfoService.splitPage(1,PAGE_SIZE);
        }
        request.setAttribute("info",info);
        return "product";
    }

    //ajax分页翻页处理
    @ResponseBody
    @RequestMapping("/ajaxsplit")
    public void ajaxsplit(ProductInfoVo vo, HttpSession session){
        //取得当前page参数的页面的数据
        PageInfo info = productInfoService.splitPageCondition(vo,PAGE_SIZE);
        session.setAttribute("info",info);
    }

    //异步ajax文件上传处理
    @ResponseBody   //用于处理ajax请求
    @RequestMapping("/ajaxImg")
    public Object ajaxImg(MultipartFile pimage,HttpServletRequest request){
        //提取生成文件名——UUID+上传图片的后缀
        saveFileName = FileNameUtil.getUUIDFileName() + FileNameUtil.getFileType(pimage.getOriginalFilename());
        //得到项目的存储路径
        String path = request.getServletContext().getRealPath("/image_big");
        //转存
        try {
            pimage.transferTo(new File(path + File.separator + saveFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回客户端JSON对象，封装图片的路径，为了在页面实现立即回显
        JSONObject object = new JSONObject();
        object.put("imgurl",saveFileName);

        return object.toString();
    }

    @RequestMapping("/save")
    public String save(ProductInfo info,HttpServletRequest request){
        info.setpImage(saveFileName);
        info.setpDate(new Date());
        int num = -1;
        try{
            num = productInfoService.save(info);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(num>0){
            request.setAttribute("msg","增加成功！");
        }else{
            request.setAttribute("msg","增加失败！");
        }
        //清空saveFileName
        saveFileName = "";
        //增加成功后应该重新访问数据库，所以要跳转到分页显示的action
        return "forward:/prod/split.action";
    }

    @RequestMapping("/one")
    public String one(int pid,ProductInfoVo vo, Model model,HttpSession session){
        ProductInfo info = productInfoService.getById(pid);
        model.addAttribute("prod",info);
        //将多条件及页码放入session中，更新处理后分页时读取条件和页码
        session.setAttribute("prodVo",vo);
        return "update";
    }

    @RequestMapping("/update")
    public String update(ProductInfo info,HttpServletRequest request){
        //如果图片有上传过，则saveFileName非空
        //如果saveFileName为空，则使用实体类info的隐藏表单域提供上来的pImage原始图片的名称
        if(!saveFileName.equals("")){
            info.setpImage(saveFileName);
        }
        //完成更新处理
        int num = -1;
        try{
            num = productInfoService.update(info);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(num>0){
            request.setAttribute("msg","更新成功！");
        }else{
            request.setAttribute("msg","更新失败！");
        }
        saveFileName = "";
        return "forward:/prod/split.action";
    }

    @RequestMapping("/delete")
    public String delete(int pid,ProductInfoVo vo,HttpServletRequest request){
        int num = -1;
        try{
            num = productInfoService.delete(pid);
        }catch (Exception e){
            e.printStackTrace();
        }

        if(num>0){
            request.setAttribute("msg","删除成功！");
            request.setAttribute("deleteProdVo",vo);
        }else{
            request.setAttribute("msg","删除失败！");
        }
        //删除结束后跳到分页显示
        return "forward:/prod/deleteAjaxSplit.action";
    }

    @ResponseBody
    @RequestMapping(value = "/deleteAjaxSplit",produces = "text/html;charset=UTF-8")
    public Object deleteAjaxSplit(HttpServletRequest request){
        PageInfo info = null;
        Object vo = request.getAttribute("deleteProdVo");
        if(vo != null){
            info = productInfoService.splitPageCondition((ProductInfoVo) vo,PAGE_SIZE);
            request.removeAttribute("deleteProdVo");
        }else{
            //取得第一页的数据
            info = productInfoService.splitPage(1,PAGE_SIZE);
        }

        request.getSession().setAttribute("info",info);
        return request.getAttribute("msg");
    }

    @RequestMapping("/deleteBatch")
    public String deleteBatch(String pids,HttpServletRequest request){
        String[] ids = pids.split(",");

        try{
            int num = productInfoService.batchDelete(ids);
            if(num>0){
                request.setAttribute("msg","批量删除成功！");
            }else{
                request.setAttribute("msg","批量删除失败！");
            }
        }catch (Exception e){
            request.setAttribute("msg","商品不可删除！");
        }
        return "forward:/prod/deleteAjaxSplit.action";
    }

    @ResponseBody
    @RequestMapping("/condition")
    public void condition(ProductInfoVo vo,HttpSession session){
        System.out.println(vo);
        List<ProductInfo> list = productInfoService.selectCondition(vo);
        PageInfo info = new PageInfo(list);
        session.setAttribute("info",info);
        //session.setAttribute("list",list);
    }


}
